package com.example.demo.jobs;

import com.example.demo.config.SpringContext;
import com.example.demo.json.JacksonUtil;
import com.example.demo.models.TaskEntity;
import com.example.demo.service.ITestService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @author Liunh
 */
@Slf4j
@Component
public class TestJob extends QuartzJobBean {

    /**
     * 不能用构造方法注入
     */
    @Resource
    private ITestService testService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("正在执行的定时任务为" + context.getMergedJobDataMap().get("ScheduleTask"));
        String jsonJob = context.getMergedJobDataMap().getString("ScheduleTask");
        TaskEntity scheduleJob = JacksonUtil.jsonToBean(jsonJob, TaskEntity.class);
        try {
            if (scheduleJob != null) {
                Object bean = SpringContext.getBean(scheduleJob.getJobClass());
                Method declaredMethod = bean.getClass().getDeclaredMethod(scheduleJob.getJobName());
                ReflectionUtils.makeAccessible(declaredMethod);
                declaredMethod.invoke(bean);
            }
        } catch (Exception e) {
            log.info(e.toString());
        }
        log.info("定时任务结束");
    }

}
